package netool

import (
	"encoding/binary"
	"github.com/go-netty/go-netty"
	"github.com/go-netty/go-netty-transport/websocket"
	"github.com/go-netty/go-netty/codec/frame"
	"net/http"
	"snow-im/app/utils"
	"time"
)

func StartTcp(address map[string]string, handler MsgHandler) {
	var logic LogicHandler = LogicHandler{
		Handler: handler,
	}
	for k, v := range address {
		var childInitializer = func(channel netty.Channel) {
			channel.Pipeline().

				AddLast(frame.LengthFieldCodec(binary.LittleEndian, 102400, 0, 2, 0, 2)).
				AddLast(logic)
				// 解包出来的bytes转换为字符串
				// 日志处理器, 打印连接建立断开消息，收到的消息

		}
		if k == "tcp" {
			// 创建Bootstrap & 监听端口 & 接受连接
			netty.NewBootstrap(netty.WithChildInitializer(childInitializer)).
				Listen(":" + v).Async(func(err error) {
				utils.Log(nil,"tcp err",err)
			})
		} else if k == "websocket" {
			var childInitializer = func(channel netty.Channel) {
				channel.Pipeline().
					AddLast(SelfPacketCodec(2)).
					AddLast(logic)
				// 解包出来的bytes转换为字符串
				// 日志处理器, 打印连接建立断开消息，收到的消息

			}
			options := &websocket.Options{
				Timeout:  time.Second * 5,
				ServeMux: http.NewServeMux(),
				Binary: true,
			}
			netty.NewBootstrap(netty.WithChildInitializer(childInitializer), netty.WithTransport(websocket.New())).
				Listen("0.0.0.0:"+v+"/chat", websocket.WithOptions(options)).Async(func(err error) {
				utils.Log(nil,"web err",err)
			})
		}

	}
	select {}
}
